package com.audiocn.engine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Process;
import android.text.format.DateFormat;

import com.audiocn.Utils.ConnServerHelper;
import com.audiocn.Utils.Log;
import com.audiocn.Utils.MD5;
import com.audiocn.Utils.Utils;
import com.audiocn.manager.PostersManager;
import com.audiocn.model.BaoBeiDescModel;
import com.audiocn.model.PosterModel;
import com.audiocn.model.PostersChanelModel;
import com.audiocn.model.PostersModel;
import com.audiocn.poster.Configs;

/**
 * 画报列表初始化引擎
 */
public class PostersEngine {
	
	private static int firCom = -1;
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	HttpParams httpParameters = new BasicHttpParams();
	HttpClient hc = null;
	Map<String, String> map = new HashMap<String, String>();
	HttpEntity entity = null;
	ResponseHandler<String> responseHandler = new BasicResponseHandler();
	PostersManager manager = null;
	
	Map<String, Thread> threads;
	List<Thread> ths;
	
	public static String POSTERS = "posters";
	public static String POSTER = "poster";
	public static String POSTER_CHANEL = "poster_chanel";
	public static String POSTERSIMG = "postersImg";
	public static String POSTERIMG = "posterImg";
	public static String POSTERBUY = "posterBuy";
	
	static Context context = null;
	
	public PostersEngine(PostersManager manager, Context context) {
		this.manager = manager;
		HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
		HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000);
		threads = new HashMap<String, Thread>();
		ths = new ArrayList<Thread>();
		PostersEngine.context = context;
	}
	/**
	 * 得到画报列表
	 * @param posters 
	 */
	public void getPostersList(final List<List<PostersModel>> posters, final int page) {
		Thread t = new Thread() {
			boolean flag = false;
			@Override
			public void run() {
				if (manager != null && threads != null) {
					try {
						if (!Configs.isCheck) {
							ConnServerHelper.checkUser();
						}
						connFirst();
						String result = getTaoBaoPostersList(page);
						parsePostersResult(result, posters);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (!flag) {
						manager.sendEmptyMessage(4);
					}
					threads.remove(POSTERS);
				}
				super.run();
			}

			@Override
			public void interrupt() {
				flag = true;
				super.interrupt();
			}
			
		};
		threads.put(POSTERS, t);
		t.start();
	}
	
	/**
	 * 获取画报详情列表
	 * @param posterId 获取的画报的Id
	 */
	public void getPosterList(final String posterId, final List<PosterModel> posters) {
		if(posters == null) {
			return;
		}
		Thread t = new Thread(){
			boolean flag = false;
			@Override
			public void run() {
				if (manager != null && threads != null) {
					try {
						String result = getTaoBaoPosterList(posterId.trim());
						parsePosterResult(result, posters);
					} catch (Exception e) {
						e.printStackTrace();
					} 
					if (!flag) {
						manager.sendMessage(manager.obtainMessage(2, posters));
						getTaoBaoPosterCommodityList(posterId, posters);
						convertToCommodity(posters);
						manager.sendEmptyMessage(15);
					}
					if (!flag) {
						manager.sendEmptyMessage(6);
						manager.sendMessageDelayed(manager.obtainMessage(6), 500);
					}
				}
				threads.remove(POSTER);
				super.run();
			}
			@Override
			public void interrupt() {
				flag = true;
				super.interrupt();
			}
		};
		threads.put(POSTER, t);
		t.start();
	}
	/**
	 * 动态的初始化画报列表的图片
	 */
	public void initPostersImage(final Map<String, String> imgs, final List<List<PostersModel>> data){
		if (imgs == null) {
			return;
		}
		Thread t = new Thread(){
			boolean flag = false;
			@Override
			public void run() {
				int i = 0;
				int j = 0;
				if (manager != null && data != null && threads != null) {
					List<List<PostersModel>> posters = data;
					File dir = new File(Configs.tlcyImgPath);
					if (!dir.exists()) {
						dir.mkdir();
					}
					while (i < posters.size() && !flag) {
						List<PostersModel> p = posters.get(i);
						j = 0;
						while (j < p.size() && !flag) {
							FileOutputStream fos = null;
							InputStream is = null;
							try {
								if (imgs.get(p.get(j).getBigImage()) != null) {
									i ++;
									continue;
								}
								String url = p.get(j).getBigImage() + "_120x120.jpg";
								URL uri = new URL(url);
								URLConnection conn = uri.openConnection();
								conn.setConnectTimeout(5 * 1000);
								conn.connect();
								is = conn.getInputStream();
								File img = new File(dir, System.currentTimeMillis() + ".jpg");
								if (img.exists()) {
									img.delete();
								}
								String path = img.getAbsolutePath();
								fos = new FileOutputStream(img);
								fos.write(Utils.getInputData(is));
								fos.flush();
								imgs.put(p.get(j).getBigImage(), path);
								
							} catch(Exception e) {
								e.printStackTrace();
							} finally {
								try {
									if (is != null) {
										is.close();
										is = null;
									}
									if (fos != null) {
										fos.close();
										fos = null;
									}
								} catch (IOException e) {
									e.printStackTrace();
								}
								j ++;
							}
						}
						if (i < 2 && !flag) {
							manager.sendMessage(manager.obtainMessage(0, i, j));
						}
						i ++;
					}
					threads.remove(POSTERSIMG);
				}
				super.run();
			}
			@Override
			public void interrupt() {
				flag = true;
				super.interrupt();
			}
			
		};
		threads.put(POSTERSIMG, t);
		t.start();
	}
	
	/**
	 * 动态的初始化画报详情列表的图片
	 */
	public void initPosterImage(final Map<String, String> imgs, final List<PosterModel> data){
		if (imgs == null) {
			return;
		}
		Thread t = new Thread(){
			boolean flag = false;
			@Override
			public void run() {
				int i = 0;
				if (manager != null && data != null && threads != null) {
					
					List<PosterModel> dcData = data;
					InputStream is = null;
					File dir = new File(Configs.tlcyImgPath);
					if (!dir.exists()) {
						dir.mkdir();
					}
					while (i < dcData.size() && !flag) {
						FileOutputStream fos = null;
						try {
							if (imgs.get(dcData.get(i).getImgUrl()) != null) {
								i ++;
								continue;
							}
							URL uri = new URL(dcData.get(i).getImgUrl() + "_310x310.jpg");
							URLConnection conn = uri.openConnection();
							conn.setConnectTimeout(5 * 1000);
							conn.connect();
							is = conn.getInputStream();
							File img = new File(dir, System.currentTimeMillis() + ".jpg");
							if (img.exists()) {
								img.delete();
							}
							String path = img.getAbsolutePath();
							fos = new FileOutputStream(img);
							fos.write(Utils.getInputData(is));
							fos.flush();
							imgs.put(dcData.get(i).getImgUrl(), path);
							if (i < 3 && !flag) {
								manager.sendMessage(manager.obtainMessage(3, i, 0));
							} 
						} catch(Exception e) {
							e.printStackTrace();
						} finally {
							i ++;
							try {
								if (is != null) {
									is.close();
								}
								if (fos != null) {
									fos.close();
								}
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						
					}
					threads.remove(POSTERIMG);
				}
				super.run();
			}
			@Override
			public void interrupt() {
				flag = true;
				super.interrupt();
			}
			
		};
		threads.put(POSTERIMG, t);
		t.start();
	}
	public void getPosterChanels(final List<PostersChanelModel> data) {
		
		if (data == null) {
			return;
		}
		
		Thread t = new Thread(){
			boolean flag = false;
			@Override
			public void run() {
				if (manager != null && threads != null) {
					try {
						getTaoBaoPosterChanelList(data);
					} catch (Exception e) {
						e.printStackTrace();
					} 
					if (!flag) {
						manager.sendEmptyMessage(10);
					}
				}
				threads.remove(POSTER_CHANEL);
				super.run();
			}
			@Override
			public void interrupt() {
				flag = true;
				super.interrupt();
			}
		};
		threads.put(POSTER_CHANEL, t);
		t.start();
		
	}
	
	private String getTaoBaoPosterChanelList(List<PostersChanelModel> data) {
		
		if (params == null) {
			params = new ArrayList<NameValuePair>();
		}
		if (map == null) {
			map = new HashMap<String, String>();
		}
		
		params.clear();
		try {
			if (hc != null) {
				hc.getConnectionManager().shutdown();
			}
		} catch (Exception e) {
		} finally {
			hc = new DefaultHttpClient(httpParameters);
		}
		map.clear();
		String chanelId = context.getSharedPreferences(PostersManager.USER_POSTERS_CHANEL, Context.MODE_APPEND).getString("chanel_id", "");
		if (chanelId == null || chanelId.trim().equals("")) {
			chanelId = "9";
		}
		String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date()).toString();
		map.put("method", "taobao.huabao.channels.get");
		map.put("timestamp", date);
		map.put("app_key", "12196345");
		map.put("v", "2.0");
		map.put("sign_method", "md5");
		map.put("channel_id", chanelId);
		map.put("format", "json");
		
		HttpPost post = new HttpPost("http://gw.api.taobao.com/router/rest");
		params.add(new BasicNameValuePair("method", "taobao.huabao.channels.get"));
		params.add(new BasicNameValuePair("timestamp", date)); 
		params.add(new BasicNameValuePair("app_key", "12196345"));
		params.add(new BasicNameValuePair("v", "2.0"));
		params.add(new BasicNameValuePair("sign", orderMap(map)));
		params.add(new BasicNameValuePair("sign_method", "md5"));
		params.add(new BasicNameValuePair("channel_id", chanelId));
		params.add(new BasicNameValuePair("format", "json"));
		String responseBody = "";
		try {
			entity = new UrlEncodedFormEntity(params, "UTF-8");
			post.setEntity(entity);
			responseBody = hc.execute(post, responseHandler);
			parsePostersChanel(responseBody, data);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	private void parsePostersChanel(String responseBody, List<PostersChanelModel> data) {
		if (data == null) {
			return;
		}
		String str = null;
		try {
			str = new String(responseBody.getBytes("UTF-8"), "UTF-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		JSONObject root;
		try {
			root = new JSONObject(str.replaceAll("\n", ".").replaceAll("\r", ".").replaceAll("\n\r", "."));
			JSONObject rsp = root.getJSONObject("huabao_channels_get_response");
			JSONObject item = rsp.getJSONObject("channels");
			JSONArray items = item.getJSONArray("poster_channel");
			for (int i = 0; i < items.length(); i++) {
				PostersChanelModel pcm = new PostersChanelModel();
				pcm.setName(items.getJSONObject(i).getString("cn_name"));
				if (!items.getJSONObject(i).isNull("desc")) {
					pcm.setDesc(items.getJSONObject(i).getString("desc"));
				}
				pcm.setId(items.getJSONObject(i).getString("id"));
				data.add(pcm);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 从WebService得到画报列表数据 "http://gw.api.taobao.com/router/rest", "taobao.huabao.posters.get"
	 * @return 得到的数据
	 */
	public String getTaoBaoPostersList(int page) {
		if (params == null) {
			params = new ArrayList<NameValuePair>();
		}
		if (map == null) {
			map = new HashMap<String, String>();
		}
		
		params.clear();
		try {
			if (hc != null) {
				hc.getConnectionManager().shutdown();
			}
		} catch (Exception e) {
		} finally {
			hc = new DefaultHttpClient(httpParameters);
		}
		map.clear();
		String chanelId = context.getSharedPreferences(PostersManager.USER_POSTERS_CHANEL, Context.MODE_APPEND).getString("chanel_id", "");
		if (chanelId == null || chanelId.trim().equals("")) {
			chanelId = "9";
		}
		
		String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date()).toString();
		map.put("method", "taobao.huabao.posters.get");
		map.put("timestamp", date);
		map.put("app_key", "12196345");
		map.put("v", "2.0");
		map.put("sign_method", "md5");
		map.put("channel_id", chanelId);
		map.put("format", "json");
		map.put("page_size", "100");
		map.put("page_no", page + "");
		
		HttpPost post = new HttpPost("http://gw.api.taobao.com/router/rest");
		params.add(new BasicNameValuePair("method", "taobao.huabao.posters.get"));
		params.add(new BasicNameValuePair("timestamp", date)); 
		params.add(new BasicNameValuePair("app_key", "12196345"));
		params.add(new BasicNameValuePair("v", "2.0"));
		params.add(new BasicNameValuePair("sign", orderMap(map)));
		params.add(new BasicNameValuePair("sign_method", "md5"));
		params.add(new BasicNameValuePair("channel_id", chanelId));
		params.add(new BasicNameValuePair("page_size", "100"));
		params.add(new BasicNameValuePair("format", "json"));
		params.add(new BasicNameValuePair("page_no", page + ""));
		String responseBody = "";
		try {
			entity = new UrlEncodedFormEntity(params, "UTF-8");
			post.setEntity(entity);
			responseBody = hc.execute(post, responseHandler);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return responseBody;
	}
	/**
	 * 根据画报Id获取画报详情列表 "http://gw.api.taobao.com/router/rest", "taobao.huabao.poster.get"
	 * @param posterId 画报ID
	 * @return 获取的数据
	 */
	public String getTaoBaoPosterList(String posterId) {
		if (posterId == null) {
			return "";
		}
		if (params == null) {
			params = new ArrayList<NameValuePair>();
		}
		if (map == null) {
			map = new HashMap<String, String>();
		}
		params.clear();
		try {
			if (hc != null) {
				hc.getConnectionManager().shutdown();
			}
		} catch (Exception e) {
		} finally {
			hc = new DefaultHttpClient(httpParameters);
		}
		map.clear();
		
		String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date()).toString();
		map.put("method", "taobao.huabao.poster.get");
		map.put("timestamp", date);
		map.put("app_key", "12196345");
		map.put("v", "2.0");
		map.put("sign_method", "md5");
		map.put("format", "json");
		map.put("poster_id", posterId.trim());
		
		HttpPost post = new HttpPost("http://gw.api.taobao.com/router/rest");
		params.add(new BasicNameValuePair("method", "taobao.huabao.poster.get"));
		params.add(new BasicNameValuePair("timestamp", date)); 
		params.add(new BasicNameValuePair("app_key", "12196345"));
		params.add(new BasicNameValuePair("v", "2.0"));
		params.add(new BasicNameValuePair("sign", orderMap(map)));
		params.add(new BasicNameValuePair("sign_method", "md5"));
		params.add(new BasicNameValuePair("format", "json"));
		params.add(new BasicNameValuePair("poster_id", posterId.trim()));
		String responseBody = "";
		try {
			entity = new UrlEncodedFormEntity(params, "UTF-8");
			post.setEntity(entity);
			if (post != null) {
				responseBody = hc.execute(post, responseHandler);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		return responseBody;
	}
	
	public void getThePositionPosters(final int position, final List<List<PostersModel>> posters) {
		if (((position < 0 || position >= posters.size()) || firCom == position) && position != 0) {
			return;
		}
		try {
			if (null != ths && ths.size() != 0) {
				try {
					Iterator<Thread> iterator = ths.iterator();
					while (iterator.hasNext()) {
						Thread t = iterator.next();
						if (t.isAlive()) {
							t.interrupt();
						}
					}
					ths.clear();
				} catch (Exception e) {
				}
			}
			firCom = position;
			int size = posters.get(position).size();
			for (int i = 0; i < size; i++) {
				if (PostersManager.imgs_posters.containsKey(posters.get(position).get(i).getBigImage())) {
					continue;
				}
				final String url = posters.get(position).get(i).getBigImage();
				Thread t = new Thread() {
					HttpURLConnection conn = null;
					boolean flag = false;
					int p = position;
					@Override
					public void interrupt() {
						flag = true;
						if (conn != null) {
							conn.disconnect();
							conn = null;
						}
						super.interrupt();
					}
					@Override
					public void run() {
						
						Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
						
						try{
							Log.e("getThePositionPosters", url);
							if (!flag && p == firCom) {
								File dir = new File(Configs.tlcyImgPath);
								if (!dir.exists()) {
									dir.mkdir();
								}
								FileOutputStream fos = null;
								InputStream is = null;
								try {
									if (PostersManager.imgs_posters.get(url) == null) {
										URL uri = new URL(url);
										conn = (HttpURLConnection) uri.openConnection();
										conn.setConnectTimeout(3 * 1000);
										try{
											conn.connect();
											for (int j = 0; j < 3; j++) {
												if (conn.getResponseCode() != 200) {
													if (j == 2) {
														conn.setConnectTimeout(5 * 1000);
													}
													conn.connect();
												} else {
													break;
												}
											}
										} catch(Exception e) {
											for (int j = 0; j < 3; j++) {
												if (conn.getResponseCode() != 200) {
													if (j == 2) {
														conn.setConnectTimeout(5 * 1000);
													}
													conn.connect();
												} else {
													break;
												}
											}
										}
										
										is = conn.getInputStream();
										File img = new File(dir, System.currentTimeMillis() + ".jpg");
										if (img.exists()) {
											img.delete();
										}
										String path = img.getAbsolutePath();
										fos = new FileOutputStream(img);
										if (fos != null && is != null) {
											byte[] b = Utils.getInputData(is);
											if (b != null) {
												fos.write(b);
												fos.flush();
												PostersManager.imgs_posters.put(url, path);
											}
										}
									}
								} catch(Exception e) {
									e.printStackTrace();
								} finally {
									try {
										if (is != null) {
											is.close();
											is = null;
										}
										if (fos != null) {
											fos.close();
											fos = null;
										}
										if (conn != null) {
											conn.disconnect();
											conn = null;
										}
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
							}
							ths.remove(this);
							if (!flag) {
								manager.sendEmptyMessage(0);
							}
							super.run();
						} catch(Exception e) {
							e.printStackTrace();
						}
					}
				};
				ths.add(t);
				t.start();
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void getThePositionPoster(final int position, final List<PosterModel> poster) {
		if (((position < 0 && position >= poster.size()) || firCom == position) && position != 0) {
			return;
		}
		try {
			if (null != ths && ths.size() != 0) {
				Iterator<Thread> iterator = ths.iterator();
				while (iterator.hasNext()) {
					Thread t = iterator.next();
					if (t.isAlive()) {
						t.interrupt();
					}
				}
				ths.clear();
			}
			firCom = position;
			if (!PostersManager.imgs_posters.containsKey(poster.get(position).getImgUrl())) {
				Thread t = new Thread() {
					HttpURLConnection conn = null;
					boolean flag = false;
					int p = position;
					@Override
					public void interrupt() {
						flag = true;
						if (conn != null) {
							conn.disconnect();
							conn = null;
						}
						super.interrupt();
					}
					@Override
					public void run() {
						
						Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
						
						try{
							if (!flag && p == firCom) {
								File dir = new File(Configs.tlcyImgPath);
								if (!dir.exists()) {
									dir.mkdir();
								}
								PosterModel p = poster.get(position);
								FileOutputStream fos = null;
								InputStream is = null;
								try {
									if (PostersManager.imgs.get(p.getImgUrl()) == null) {
										String url = p.getImgUrl();
										URL uri = new URL(url);
										conn = (HttpURLConnection) uri.openConnection();
										conn.setConnectTimeout(3 * 1000);
										try {
											conn.connect();
											for (int j = 0; j < 3; j++) {
												if (conn.getResponseCode() != 200) {
													if (j == 2) {
														conn.setConnectTimeout(5 * 1000);
													}
													conn.connect();
												} else {
													break;
												}
											}
										} catch(Exception e) {
											for (int j = 0; j < 3; j++) {
												if (conn.getResponseCode() != 200) {
													if (j == 2) {
														conn.setConnectTimeout(5 * 1000);
													}
													conn.connect();
												} else {
													break;
												}
											}
										}
										is = conn.getInputStream();
										File img = new File(dir, System.currentTimeMillis() + ".jpg");
										if (img.exists()) {
											img.delete();
										}
										String path = img.getAbsolutePath();
										fos = new FileOutputStream(img);
										if (fos != null && is != null) {
											byte[] b = Utils.getInputData(is);
											if (b != null) {
												fos.write(b);
												fos.flush();
												PostersManager.imgs.put(p.getImgUrl(), path);
											}
										}
									}
								} catch(Exception e) {
									e.printStackTrace();
								} finally {
									try {
										if (is != null) {
											is.close();
											is = null;
										}
										if (fos != null) {
											fos.close();
											fos = null;
										}
										if (conn != null) {
											conn.disconnect();
											conn = null;
										}
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
							}
							ths.remove(this);
							if (!flag) {
								manager.sendEmptyMessage(3);
							}
							super.run();
						} catch(Exception e) {
							e.printStackTrace();
						}
					}
				};
				ths.add(t);
				t.start();
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据画报Id获取画报商品信息
	 * @param posterId 画报ID
	 * @return 获取的数据
	 */
	public String getTaoBaoPosterCommodityList(String posterId, List<PosterModel> posters) {
		if (posterId == null) {
			return "";
		}
		if (params == null) {
			params = new ArrayList<NameValuePair>();
		}
		if (map == null) {
			map = new HashMap<String, String>();
		}
		params.clear();
		try {
			if (hc != null) {
				hc.getConnectionManager().shutdown();
			}
		} catch (Exception e) {
		} finally {
			hc = new DefaultHttpClient(httpParameters);
		}
		map.clear();
		
		String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date()).toString();
		map.put("method", "taobao.huabao.poster.goodsinfo.get");
		map.put("timestamp", date);
		map.put("app_key", "12196345");
		map.put("v", "2.0");
		map.put("sign_method", "md5");
		map.put("format", "json");
		map.put("poster_id", posterId.trim());
		Log.e("posterId", "posterId");
		HttpPost post = new HttpPost("http://gw.api.taobao.com/router/rest");
		params.add(new BasicNameValuePair("method", "taobao.huabao.poster.goodsinfo.get"));
		params.add(new BasicNameValuePair("timestamp", date)); 
		params.add(new BasicNameValuePair("app_key", "12196345"));
		params.add(new BasicNameValuePair("v", "2.0"));
		params.add(new BasicNameValuePair("sign", orderMap(map)));
		params.add(new BasicNameValuePair("sign_method", "md5"));
		params.add(new BasicNameValuePair("format", "json"));
		params.add(new BasicNameValuePair("poster_id", posterId.trim()));
		String responseBody = "";
		try {
			entity = new UrlEncodedFormEntity(params, "UTF-8");
			post.setEntity(entity);
			if (post != null) {
				responseBody = hc.execute(post, responseHandler);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		return parseTaoBaoCommodity(responseBody, posters);
	}
	/**
	 * 转化淘宝客
	 * @param key 关键字
	 * @return 获取结果
	 */
	protected void convertToCommodity(List<PosterModel> posters) {
		if (params == null) {
			params = new ArrayList<NameValuePair>();
		}
		if (map == null) {
			map = new HashMap<String, String>();
		}
		String date = DateFormat.format("yyyy-MM-dd hh:mm:ss", new Date()).toString();
		List<String> strs = getCommodityIdParam(posters);
		if (strs != null) {
			for (int i = 0; i < strs.size(); i++) {
				params.clear();
				try {
					if (hc != null) {
						hc.getConnectionManager().shutdown();
					}
				} catch (Exception e) {
				} finally {
					hc = new DefaultHttpClient(httpParameters);
				}
				map.clear();
				map.put("method", "taobao.taobaoke.items.convert");
				map.put("timestamp", date);
				map.put("app_key", "12196345");
				map.put("v", "2.0");
				map.put("sign_method", "md5");
				map.put("format", "json");
				map.put("fields", "num_iid,title,nick,pic_url,price,click_url,commission," +
				"commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume ");
				map.put("pid", Configs.pid);
				map.put("num_iids", strs.get(i));
				Log.e("strs.get(i)", strs.get(i));
				HttpPost post = new HttpPost("http://gw.api.taobao.com/router/rest");
				params.add(new BasicNameValuePair("method", "taobao.taobaoke.items.convert"));
				params.add(new BasicNameValuePair("timestamp", date)); 
				params.add(new BasicNameValuePair("app_key", "12196345"));
				params.add(new BasicNameValuePair("v", "2.0"));
				params.add(new BasicNameValuePair("sign", orderMap(map)));
				params.add(new BasicNameValuePair("sign_method", "md5"));
				params.add(new BasicNameValuePair("format", "json"));
				params.add(new BasicNameValuePair("fields", "num_iid,title,nick,pic_url,price,click_url," +
				"commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume "));
				params.add(new BasicNameValuePair("pid", Configs.pid));
				params.add(new BasicNameValuePair("num_iids", strs.get(i)));
				String responseBody = "";
				try {
					entity = new UrlEncodedFormEntity(params, "UTF-8");
					post.setEntity(entity);
					responseBody = hc.execute(post, responseHandler);
					parseCommodity(responseBody, posters);
				} catch(Exception e){
					e.printStackTrace();
				} finally {
					if (hc != null) {
						hc.getConnectionManager().shutdown();
					}
				}
			}
			removeNull(posters);
		}
	}
	
	private void removeNull(List<PosterModel> posters) {
		boolean flag = false;
		for (int i = 0; i < posters.size(); i++) {
			if (posters.get(i).getBbs() != null) {
				for (int j = 0; j < posters.get(i).getBbs().size(); j++) {
					if (posters.get(i).getBbs().get(j).getTitle() == null || posters.get(i).getBbs().get(j).getTitle().trim().equals("") || 
							posters.get(i).getBbs().get(j).getPic_url() == null) {
						posters.get(i).getBbs().remove(j);
						j = 0;
					} else if(!flag) {
						Log.e("removeNull", "i:" + i + " j:" + j);
						manager.sendMessage(manager.obtainMessage(15, posters.get(i).getBbs().get(j)));
						flag = true;
					}
				}
			}
		}
	}
	private void parseCommodity(String result, List<PosterModel> posters) {
		if (result == null || posters == null) {
			return;
		}
		JSONObject root;
		try {
			root = new JSONObject(result.toString());
			Log.e("result", result);
			JSONObject rsp = root.getJSONObject("taobaoke_items_convert_response");
			JSONObject item = rsp.getJSONObject("taobaoke_items");
			JSONArray items = item.getJSONArray("taobaoke_item");
			for (int i = 0; i < items.length(); i++) {
				BaoBeiDescModel bb = new BaoBeiDescModel();
				bb.setId(items.getJSONObject(i).getString("num_iid"));
				for (int j = 0; j < posters.size(); j++) {
					for (int j2 = 0; j2 < posters.get(j).getBbs().size(); j2++) {
						if (posters.get(j).getBbs().get(j2).getId().equals(bb.getId())) {
							posters.get(j).getBbs().get(j2).setClick_url(items.getJSONObject(i).getString("click_url"));
							posters.get(j).getBbs().get(j2).setPic_url(items.getJSONObject(i).getString("pic_url"));
							posters.get(j).getBbs().get(j2).setPrice(items.getJSONObject(i).getString("price"));
							posters.get(j).getBbs().get(j2).setTitle(items.getJSONObject(i).getString("title"));
							posters.get(j).getBbs().get(j2).setLocation(items.getJSONObject(i).getString("item_location"));
							posters.get(j).getBbs().get(j2).setSeller_credit_score(items.getJSONObject(i).getString("seller_credit_score"));
							posters.get(j).getBbs().get(j2).setVolume(items.getJSONObject(i).getString("volume"));
							posters.get(j).getBbs().get(j2).setShop_click_url(items.getJSONObject(i).getString("shop_click_url"));
							posters.get(j).getBbs().get(j2).setCommission(items.getJSONObject(i).getString("commission"));
							posters.get(j).getBbs().get(j2).setCommission_num(items.getJSONObject(i).getString("commission_num"));
							posters.get(j).getBbs().get(j2).setCommission_rate(items.getJSONObject(i).getString("commission_rate"));
							posters.get(j).getBbs().get(j2).setCommission_volume(items.getJSONObject(i).getString("commission_volume"));
							posters.get(j).getBbs().get(j2).setNick(items.getJSONObject(i).getString("nick"));
						}
					}
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析得到的画报数据,存储到指定的集合中
	 * @param result 画报数据
	 * @param posters 要存储的集合
	 * @throws JSONException
	 */
	public void parsePostersResult(String result, List<List<PostersModel>> posterss){
		if (result == null) {
			return;
		}
		if (posterss == null) {
			return;
		}
		JSONObject root;
		try {
			root = new JSONObject(result.toString().trim());
			JSONObject rsp = root.getJSONObject("huabao_posters_get_response");
			JSONObject item = rsp.getJSONObject("posters");
			JSONArray items = item.getJSONArray("poster");
			List<PostersModel> cach = new ArrayList<PostersModel>();
			int index = 1;
			for (int i = 0; i < items.length(); i++) {
				PostersModel poster = new PostersModel();
				int id = Integer.parseInt(items.getJSONObject(i).getString("id"));
				poster .setId(id);
				poster.setCreate(items.getJSONObject(i).getString("created"));
				poster.setModified(items.getJSONObject(i).getString("modified"));
				poster.setTitle(items.getJSONObject(i).getString("title"));
				poster.setShort_title(items.getJSONObject(i).getString("short_title"));
				poster.setTags(items.getJSONObject(i).getString("tags"));
				poster.setWeight(items.getJSONObject(i).getString("weight"));
				String[] urls = items.getJSONObject(i).getString("cover_urls").split(",");
				poster.setSmallImage(urls[0]);
				poster.setBigImage(urls[1]);
				int hits = Integer.parseInt(items.getJSONObject(i).getString("hits"));
				poster.setHits(hits);
				int channel_id = Integer.parseInt(items.getJSONObject(i).getString("channel_id"));
				poster.setChannel_id(channel_id);
				cach.add(poster);
				index ++;
				if (index == 5) {
					posterss.add(cach);
					cach = new ArrayList<PostersModel>();
					index = 1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String parseTaoBaoCommodity(String result, List<PosterModel> posters) {
		
		if (result == null || posters == null) {
			return null;
		}
		JSONObject root;
		try {
			root = new JSONObject(result.toString());
			JSONObject rsp = root.getJSONObject("huabao_poster_goodsinfo_get_response");
			JSONObject item = rsp.getJSONObject("goodsinfolist");
			JSONArray items = item.getJSONArray("poster_goods_info");
			Log.e("result", "" + result);
			for (int i = 0; i < items.length(); i++) {
				BaoBeiDescModel bb = new BaoBeiDescModel();
				bb.setId(items.getJSONObject(i).getString("num_id"));
				String pic_id = items.getJSONObject(i).getString("pic_id");
				for (int j = 0; j < posters.size(); j++) {
					if (posters.get(j).getId() != null && posters.get(j).getId().trim().equals(pic_id)) {
						posters.get(j).getBbs().add(bb);
						posters.get(j).setShort_title(items.getJSONObject(i).getString("short_title"));
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 解析画报详情列表数据,将结果存储到指定集合中
	 * @param result 画报详情数据
	 * @param posters 要存储结果的集合
	 * @throws JSONException
	 */
	public void parsePosterResult(String result, List<PosterModel> posters){
		if (result == null) {
			return;
		}
		if (posters == null) {
			posters = new ArrayList<PosterModel>();
		}
		JSONObject root;
		try {
			root = new JSONObject(result.toString());
			JSONObject rsp = root.getJSONObject("huabao_poster_get_response");
			JSONObject item = rsp.getJSONObject("pics");
			JSONArray items = item.getJSONArray("poster_picture");
			for (int i = 0; i < items.length(); i++) {
				PosterModel poster = new PosterModel();
				poster.setId(items.getJSONObject(i).getString("id"));
				String desc = items.getJSONObject(i).getString("desc").replaceAll("<br/>", "\n");
				if (desc.contains("--")) {
					desc = desc.split("--")[0];
				}
				poster.setDesc(desc);
				poster.setImgUrl(items.getJSONObject(i).getString("url"));
				poster.setBbs(new ArrayList<BaoBeiDescModel>());
				posters.add(poster);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private List<String> getCommodityIdParam(List<PosterModel> posters) {
		if (posters == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		List<String> str = new ArrayList<String>();
		int p = 0;
		for (int i = 0; i < posters.size(); i++) {
			for (int j = 0; j < posters.get(i).getBbs().size(); j++) {
				if (p == 20) {
					str.add(sb.toString().substring(0, sb.length() - 2));
					sb = new StringBuilder();
					p = 0;
				}
				sb.append(posters.get(i).getBbs().get(j).getId() + ",");
				p ++;
			}
		}
		if (p > 1) {
			str.add(sb.toString().substring(0, sb.length() - 2));
		}
		if (str.size() <= 0) {
			return null;
		}
		return str;
	}
	
	/**
	 * 按照key值从小到大的顺序对Map中的数据进行排序,生成拼接起来的字符串,并转化为全部大写的MD5码
	 * @param map 要排序的map
	 * @return 排序后生成的大写MD5码
	 */
	private String orderMap(Map<String, String> map) {
		
		if (map == null) {
			return "";
		}
		
		String[] names = new String[map.size()];
		Iterator<String> iterator = map.keySet().iterator();
		String result = null;
		int i = 0;
		while (iterator.hasNext()) {
			names[i] = iterator.next();
			i ++;
		}
		String s = null;
		for (int j = 0; j < names.length; j++) {
			for (int j2 = j+1; j2 < names.length; j2++) {
				if (names[j].compareTo(names[j2]) > 0) {
					s = names[j];
					names[j] = names[j2];
					names[j2] = s;
				}
			}
		}
		StringBuilder sb = new StringBuilder();
		sb.append("31710a2ca35f8bbd5d65333b5bfcb6d8");
		for (int j = 0; j < names.length; j++) {
			sb.append(names[j]).append(map.get(names[j]));
		}
		sb.append("31710a2ca35f8bbd5d65333b5bfcb6d8");
		result = MD5.md5Upper(sb.toString());
		return result;
	}
	/**
	 * 是否已经淘宝鉴权
	 * @author Li Hongjun
	 */
	public static boolean isFirst(){
		Log.e("isFirst", "connFirst start..");
		if(context==null){
			return true;
		}
		SharedPreferences sp = context.getSharedPreferences("UserSession", Context.MODE_APPEND);
		String str = sp.getString("request_time", "");
		String time = getCurrentTime();
		Log.e("isFirst", "request_time:(" + str + ") time:(" + time + ")");
		if (str == null || time == null || str.trim().equals("") || !str.trim().equals(time.trim())) {
			return true;
		}else{
			return false;
		}
	}
	public static void connFirst() {
		
		if (isFirst()) {
			Log.e("connFirst", "connFirst connect..");
			URL url;
			try {
				String imei = Utils.getIMEI();
				String imsi = Utils.getIMSI();
				if (imei == null) {
					imei = "000000000000001";
				}
				if (imsi == null) {
					imsi = imei;
				}	
				url = new URL("http://m.taobao.com/syscheck.htm?ttid="
						+ Configs.ttid + "&imei=" + imei + "&imsi=" 
						+ imsi + "&clt_act=startup");
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				int len=conn.getResponseCode();
				Log.e("connFirst", "connFirst responseCode="+len);
				if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
					ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
					byte[] buff = new byte[512];
					int rc = 0;
					while ((rc = conn.getInputStream().read(buff, 0, 512)) > 0) {
						swapStream.write(buff, 0, rc);
					}
					byte[] rs = swapStream.toByteArray();
					Log.e("connFirst", "connFirst rs=" + new String(rs));
					SharedPreferences sp = context.getSharedPreferences("UserSession", Context.MODE_APPEND);
					String time = getCurrentTime();
					sp.edit().putString("request_time", time).commit();
				}else{
					Log.e("connFirst", "connFirst rs=null");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.e("connFirst", "connFirst complete..");
		
	}
	
	public static String getCurrentTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}
	
	/**
	 * 根据当前第几层DC,进行相应的线程检查,并停止
	 * @param floor 取值为1或者2,如果为1,为posters层,否者为poster层
	 */
	public void stopThread(int floor) {
		Thread t;
		try {
			if (hc != null) {
				hc.getConnectionManager().shutdown();
				hc = null;
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (threads != null) {
					if (floor == 1) {
						t = threads.get(PostersEngine.POSTERS);
						if(t != null) {
							if (t.isAlive()) {
								t.interrupt();
							}
							threads.remove(PostersEngine.POSTERS);
						}
						t = threads.get(PostersEngine.POSTERSIMG);
						if(t != null) {
							if (t.isAlive()) {
								t.interrupt();
							}
							threads.remove(PostersEngine.POSTERSIMG);
						}
					} else if(floor == 2) {
						t = threads.get(PostersEngine.POSTER);
						if(t != null) {
							if (t.isAlive()) {
								t.interrupt();
							}
							threads.remove(PostersEngine.POSTER);
						}
						t = threads.get(PostersEngine.POSTERIMG);
						if(t != null) {
							if (t.isAlive()) {
								t.interrupt();
							}
							threads.remove(PostersEngine.POSTERIMG);
						}
					} else if(floor == 0){
						for(Entry<String, Thread> entry : threads.entrySet()) {
							t = (Thread)entry.getValue();
							if (t.isAlive()) {
								t.interrupt();
							}
						}
						if (ths != null) {
							Iterator<Thread> it = ths.iterator();
							while (it.hasNext()) {
								Thread tt = it.next();
								if (tt != null && tt.isAlive()) {
									tt.interrupt();
								}
							}
							ths.clear();
						}
						threads.clear();
					}
				}
			} catch (Exception e2) {
			}
		}
	}
	
	public static Bitmap fitSizePic(byte[] f) {
		if (f == null) {
			return null;
		}
		BitmapFactory.Options opts = new BitmapFactory.Options();
		if (f.length < 20480) { // 0-20k
		 opts.inSampleSize = 2;
		} else if (f.length < 51200) { // 20-50k
		 opts.inSampleSize = 2;
		}else if (f.length < 307200) { // 50-300k
		 opts.inSampleSize = 5;
		} else if (f.length < 819200) { // 300-800k
		 opts.inSampleSize = 6;
		} else if (f.length < 1048576) { // 800-1024k
		 opts.inSampleSize = 8;
		} else {
		 opts.inSampleSize = 10;
		}
		Bitmap resizeBmp = BitmapFactory.decodeByteArray(f, 0, f.length, opts);
		return resizeBmp;
	}
	public boolean isSynchronizeTaoBao() {
		if (context == null) {
			return false;
		}
		SharedPreferences sp = context.getSharedPreferences("tongbuUsers", Context.MODE_APPEND);
		return sp.getString("taoBaoUser", "0").equals("true") ? true : false;
	}

}
